import React, { useContext, useState, useEffect, useRef } from 'react';
import { Table, Input, Button, Form, Modal } from 'antd'
import axios from 'axios';
import {
    DeleteOutlined,
    EditOutlined
  } from '@ant-design/icons';
const { confirm } = Modal
//react函数组件
const NewsCategory = () => {
    //状态
    const [dataSource, setdataSource] = useState([]);
    const EditableContext = React.createContext(null);
    useEffect(()=>{
        axios.get('/categories').then(res=>{
            setdataSource(res.data)
        })
    },[])
    // table表格
    const columns = [
        {
            title: 'ID',
            dataIndex: 'id',
            render: (id)=>{
                return <b>{id}</b>
            }
        },
        {
            title: '栏目名称',
            dataIndex: 'title',
            onCell: (record) => ({
                record,
                editable: true,
                dataIndex: 'title',
                title: '栏目名称',
                handleSave: handleSave,
              }),
        },
        {
            title: '操作',
            render: (item)=>{
                return <div>
                    <Button type="primary" shape="circle"  danger icon={<DeleteOutlined />} 
                    onClick={()=>confirMothod(item)}
                    />
                </div>
            }
        },
      ];
    //删除弹框
    const confirMothod = (item) => {
        confirm({
            title: '您确定删除吗',
            icon: <EditOutlined />,
            onOk(){
                deleteMethod(item)
            },
            onCancel(){
                console.log("Can")
            }
        })
    }
    // 确认删除
    const deleteMethod = (item) => {
        setdataSource(dataSource.filter(data=>data.id!==item.id))
        axios.delete(`/categories/${item.id}`)
    }
    // 表格修改回调
    const handleSave = (record) => {
        setdataSource(dataSource.map(item=>{
            if (item.id === record.id) {
                return{
                    id: record.id,
                    title: record.title,
                    value: record.title
                }
            }else{
                return item
            }
        }))
        axios.patch(`/categories/${record.id}`, {
            title: record.title,
            value: record.title
        })
    }
    // 可编辑表格------------------------------------------------------
    const EditableRow = ({ index, ...props }) => {
        const [form] = Form.useForm();
        return (
          <Form form={form} component={false}>
            <EditableContext.Provider value={form}>
              <tr {...props} />
            </EditableContext.Provider>
          </Form>
        );
      };
      
      const EditableCell = ({
        title,
        editable,
        children,
        dataIndex,
        record,
        handleSave,
        ...restProps
      }) => {
        const [editing, setEditing] = useState(false);
        const inputRef = useRef(null);
        const form = useContext(EditableContext);
        useEffect(() => {
          if (editing) {
            inputRef.current.focus();
          }
        }, [editing]);
      
        const toggleEdit = () => {
          setEditing(!editing);
          form.setFieldsValue({
            [dataIndex]: record[dataIndex],
          });
        };
      
        const save = async () => {
          try {
            const values = await form.validateFields();
            toggleEdit();
            handleSave({ ...record, ...values });
          } catch (errInfo) {
            console.log('Save failed:', errInfo);
          }
        };
      
        let childNode = children;
      
        if (editable) {
          childNode = editing ? (
            <Form.Item
              style={{
                margin: 0,
              }}
              name={dataIndex}
              rules={[
                {
                  required: true,
                  message: `${title} is required.`,
                },
              ]}
            >
              <Input ref={inputRef} onPressEnter={save} onBlur={save} />
            </Form.Item>
          ) : (
            <div
              className="editable-cell-value-wrap"
              style={{
                paddingRight: 24,
              }}
              onClick={toggleEdit}
            >
              {children}
            </div>
          );
        }
      
        return <td {...restProps}>{childNode}</td>;
      };
      //-----------------------------------------------------------
    return (
        <div>
            <Table dataSource={dataSource} columns={columns} pagination={{pageSize:5}}
             rowKey={item=>item.id}
             components={{
                body: {
                    row: EditableRow,
                    cell: EditableCell,
                  }
             }}
             />;
        </div>
    );
};

export default NewsCategory;